package com.example.mydemo.config;

import com.example.mydemo.entity.LogBean;
import com.example.mydemo.entity.Users;
import com.example.mydemo.service.LogRepository;
import com.example.mydemo.util.IpUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.stream.Collectors;

@Component
public class RequestLogInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(RequestLogInterceptor.class);
    @Autowired
    private LogRepository logRepository;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 获取客户端真实IP（考虑代理情况）

        String ip = IpUtil.getRequestIp(request);
        Users a = (Users) request.getSession().getAttribute("user");
        // 记录请求信息
        String params = getSafeParams(request);
        LogBean log =new LogBean();
        log.setIp(ip);
        log.setClassName(request.getRequestURI());
        log.setMethod(request.getMethod());
        log.setParam(params);
        log.setCreateDate(LocalDateTime.now());
        if(a!=null){
            log.setUsername(a.getName());
            log.setUserId(a.getId());
        }
        logRepository.save(log);
        logger.info("[Request] IP: {} | Method: {} | URL: {} | Params: {} | Time: {}",
                ip,
                request.getMethod(),
                request.getRequestURI(),
                params,
                LocalDateTime.now());

        return true;
    }

    private String getSafeParams(HttpServletRequest request) {
        // 过滤敏感参数（如密码）
        return request.getParameterMap().entrySet().stream()
                .map(entry -> {
                    String key = entry.getKey();
                    String[] values = entry.getValue();
                    if (key.toLowerCase().contains("password")) {
                        return key + "=******";
                    }
                    return key + "=" + Arrays.toString(values);
                })
                .collect(Collectors.joining("&"));
    }
}